#!/usr/bin/env bash
read -p "请输入Zookeeper的版本号，如果未输入，则会自动填写版本为3.6.3：" zkver
if [ -z "$zkver" ];then
echo "您尚未输入版本已经自动为您赋值版本。"
zkver=3.6.3
fi
port=2181
wget -c https://mirrors.tuna.tsinghua.edu.cn/apache/zookeeper/zookeeper-$zkver/apache-zookeeper-$zkver-bin.tar.gz
tar zxvf zookeeper-$zkver.tar.gz
mv zookeeper-$zkver /usr/local/zookeeper
ln -s /usr/local/zookeeper/bin/* /usr/local/bin/
installhome=/usr/local/zookeeper
# 开始创建Service
servicefile=/usr/lib/systemd/system/zookeeper.service
mkdir -p /data/zookeeper

if [ ! -f "$servicefile" ]; then
  cat >$servicefile<<EOF
[Unit]
Description=Zookeeper Service
After=syslog.target

[Service]
Type=forking
WorkingDirectory=/usr/local/zookeeper
Environment=ZOO_LOG_DIR=/usr/local/zookeeper/
Environment=PATH=/usr/java/default/bin:/usr/java/default/jre/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin:/root/bin
ExecStart=/usr/local/zookeeper/bin/zkServer.sh start /usr/local/zookeeper/conf/zoo.cfg
ExecStop=/usr/local/zookeeper/bin/zkServer.sh stop /usr/local/zookeeper/conf/zoo.cfg
ExecReload=/usr/local/zookeeper/bin/zkServer.sh restart /usr/local/zookeeper/conf/zoo.cfg
SuccessExitStatus=143
KillMode=process
Restart=on-failure
RestartSec=42s


[Install]
WantedBy=multi-user.target

EOF
systemctl daemon-reload

fi
cat>$installhome/conf/zoo.cfg<<EOF
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
# do not use /tmp for storage, /tmp here is just
# example sakes.
dataDir=/data/zookeeper
# the port at which the clients will connect
clientPort=$port
# the maximum number of client connections.
# increase this if you need to handle more clients
#maxClientCnxns=60
#
# Be sure to read the maintenance section of the
# administrator guide before turning on autopurge.
#
# http://zookeeper.apache.org/doc/current/zookeeperAdmin.html#sc_maintenance
#
# The number of snapshots to retain in dataDir
#autopurge.snapRetainCount=3
# Purge task interval in hours
# Set to "0" to disable auto purge feature
#autopurge.purgeInterval=1
EOF

firewall-cmd --zone=public --permanent --add-port=$port/tcp
firewall-cmd --reload
systemctl enable zookeeper
systemctl start zookeeper

